package cz.possoft.client.loader;

import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * This class is used for scanning deploy directory periodically.
 * 
 * @author mposolda
 */
class Scanner implements Runnable {
	
	private final File deployDir = new File(DeploymentConfigConstants.DEPLOY_DIRECTORY); 
	
	public void run() {
		System.out.println("Starting scan of deploy directory.");
		while (true) {
			try {
				File[] files = scanDeployDirectory();
				LoaderHolder.getInstance().doDeployment(files);				
				Thread.sleep(DeploymentConfigConstants.SCANNING_INTERVAL);
			}
			catch (Exception e) {
				System.err.println("Exception during deployment!!!");
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * Scan deploy directory and return list of jar files in it. Checking of correction is donne according to value of attribute checkJars.
	 * This checking performs that only "jar" files should be in deploy directory and there should be only couples of "$(key)Generic.jar" and "$(key)Client.jar".
	 *  
	 * @return
	 * @throws JarDeploymentException
	 */
	File[] scanDeployDirectory() throws JarDeploymentException {
		File[] files = deployDir.listFiles();
		if (DeploymentConfigConstants.CHECK_JARS) {
			List<File> filesList = Arrays.asList(files);
			Set<File> jars = new HashSet<File>(8);
			for (File file : filesList) {
				if (file.getName().endsWith(".jar")) {
					if ((file.getName().endsWith("Generic.jar")) || (file.getName().endsWith("Client.jar"))) {
						String prefix = DeploymentUtils.getPrefixForJarFile(file.getName());
						File genericJarFile = new File(deployDir + "/" + prefix + "Generic.jar");
						File clientJarFile = new File(deployDir + "/" + prefix + "Client.jar");
						// checking if both files are in deploy directory.
						if ((filesList.contains(genericJarFile)) && (filesList.contains(clientJarFile))) {
							jars.add(genericJarFile);
							jars.add(clientJarFile);
						}
						// This means that couple of both jars is not finded. Exception can't be thrown because it's possible that only one jar 
						// file is deleted during time of checking.
						// else throw new JarDeploymentException("Both files " + genericJarFile + " and " + clientJarFile + " should be in directory " + deployDir);
					}
					else throw new JarDeploymentException("File " + file + " is not valid file for deployment in directory " + deployDir);
				}
			}
			return jars.toArray(new File[jars.size()]);
		}
		else {
			return files;
		}
	}
	
	protected File getDeployDir() {
		return deployDir;
	}

}
